# To change this template, choose Tools | Templates
# and open the template in the editor.

class MaterialsWishList < ActiveRecord::Base
  belongs_to :material, :class_name => "Material"
  belongs_to :wish_list, :class_name => "WishList"
  validates_uniqueness_of :material_id, :scope => :wish_list_id

  def self.search_with_paginate(wish_list_ids, search_title)
    internal_search(wish_list_ids, search_title, false, nil)
  end

  def self.search(wish_list_ids, search_title, page)
    internal_search(wish_list_ids, search_title, true, page)
  end

  private
  def self.internal_search(wish_list_ids, search_title, paginate, page)
    items_per_page = count_record_per_page :materials_wish_lists

    #busco a ver si lo que estamos buscando es un carrito de compras, de ser asi se lista por orden: wish_lists.name y materials.title
    #sino por wish_lists.name, order_list
    if !wish_list_ids.nil? && wish_list_ids.size == 1
      if WishList.is_cart?(wish_list_ids[0])
        order = "materials.title"
      else
        order = "wish_lists.name, order_list"
      end
    else
      order = "wish_lists.name, order_list"
    end
    
    conditions_clauses = []
    conditions_options = []

    #Si viene null significa que no hay que tomar encuenta esta condiccion
    if !wish_list_ids.nil? 
      #Si viene con algun id hay que tomar en cuenta la condiccion
      if wish_list_ids.size > 0
        ids_str = nil
        wish_list_ids.each { |id| if ids_str == nil then ids_str = id.to_s else ids_str += ",#{id.to_s}" end  }
        conditions_clauses << "wish_list_id in (#{ids_str})"
      else
        #significa que no hay que levantar nada
          conditions_clauses << "wish_list_id <> wish_list_id"
      end
    end

    if !search_title.nil? && search_title.size > 0
      conditions_clauses << "upper(materials.title) like upper(?)"
      conditions_options << "%#{search_title}%"
    end

    conditions = [conditions_clauses.join(" AND "), conditions_options].flatten

    if paginate
      materials_wish_lists = MaterialsWishList.paginate :per_page => items_per_page,:page => page, :include => [:material, :wish_list], :conditions => conditions, :order => order
    else
      materials_wish_lists = MaterialsWishList.paginate :per_page => nil, :page => nil, :include => [:material, :wish_list], :conditions => conditions, :order => order
      #materials_wish_lists = MaterialsWishList.find :all, :include => [:material, :wish_list], :conditions => conditions, :order => order
    end
    
    return materials_wish_lists
  end
end
